<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\manage\controller\admin;

use app\common\model\Message;
use buwang\base\AdminBaseController;
use buwang\traits\CrudControllerTrait;
use app\manage\model\AuthNode;
use app\manage\model\AuthGroupAccess;
use app\manage\model\Member as MemberModel;
use think\App;
use app\Request;
use think\Exception;
use app\common\model\member\Wallet;
use think\Response;

class Member extends AdminBaseController
{
    use CrudControllerTrait;

    protected $model = null;//模型实例

    protected function initialize()
    {
        parent::initialize();

        $this->model = new \app\common\model\Member();
    }

    /**
     * 租户选择列表.
     *
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function selectList():Response {
        $searchKw = $this->request->param('keywords', '');
        $onlyTop  = $this->request->param('onlyTop', FALSE);
        $where    = [];
        if ($searchKw !== '') {
            $where[] = ['nickname', 'like', "%$searchKw%"];
        }
        if ($onlyTop) {
            $where[] = ['parent_id', '=', 0];
        }
        $members = $this->model->where($where)
            ->select();

        return $this->success('ok', [
            'members' => $members,
        ]);
    }

    /**
     * 查看
     * @menu true
     */
    public function index()
    {
        if (request()->isAjax()) {
            $page = request()->get('page/d', 1);
            $limit = request()->get('limit/d', 100);
            $login_time = request()->get('login_time');
            $status = request()->get('status');

            //TODO 获取搜索条件
            //TODO 如果有不属于表内的字段,查询会报错
            $where = request()->get();
            unset($where['page']);
            unset($where['limit']);
            unset($where['login_time']);
            unset($where['status']);
            foreach ($where as $k => $v) {
                if (!$v && $v !== '0' && $v !== 0 && $v !== false) {
                    unset($where[$k]);
                }
            }
            $where1 = [];
            if (isset($login_time) && !empty($login_time)) {
                if ($login_time == 3) {
                    $where1[] = ['login_time', '>', time() - 7879680];
                }
                if ($login_time == 12) {
                    $where1[] = ['login_time', '<', time() - 31536000];
                }
            }

            if (isset($status)) {
                $where1[] = ['status', '=', $status];
            }

            try {
                $total = $this->model->where($where)->where($where1)->count();
                $groups = $this->model->where($where)->where($where1)->order($this->model->getPk(), 'DESC')->hidden(['password', 'safe_password'])->page($page, $limit)->select()->toArray();
                //全部
                $all_count = $this->model->count();
                //正常
                $normal_count = $this->model->where('status', 1)->count();
                //冻结
                $lock_count = $this->model->where('status', 0)->count();
                //三月内登录
                $in_login = $this->model->where('login_time', '>', time() - 7879680)->count();
                //一年未登录
                $out_login = $this->model->where('login_time', '<', time() - 31536000)->count();
                //统计数据
                $statistics = [
                    'all_count' => $all_count,
                    'normal_count' => $normal_count,
                    'lock_count' => $lock_count,
                    'in_login' => $in_login,
                    'out_login' => $out_login,
                ];
                $list = array();
                $memberConfigIds = array();
                //组合树
                foreach ($groups as $val) {
                    $memberConfigIds[] = $val['id'];
                }

                foreach ($groups as $group) {
                    $data = $group;
                    //得到租户的钱包类型
                    $data['wallet'] = Wallet::where('member_id', $group['id'])->find();
                    $data['is_top'] = false;
                    if ($group['parent_id'] == 0) $data['is_top'] = true;
                    $data['rules'] = [];
                    $data['auth_group_access'] = [];
                    //查询所有角色，以逗号拼接
                    $rules = AuthGroupAccess::valiWhere()->where('uid', $group['id'])->where('scopes', 'member')->column('group_id');
                    $names = AuthGroupAccess::valiWhere()->where('uid', $group['id'])->where('scopes', 'member')->column('name');
                    if ($rules) {
                        $data['rules'] = $rules;
                    }
                    if ($names) {
                        $data['auth_group_access'] = $names;
                    }
                    //列表中不存在该父id则父id为0
                    if (!in_array($group['parent_id'], $memberConfigIds)) $data['parent_id'] = 0;
                    $list[] = $data;
                }
                $list = array_merge(AuthNode::tree($list, 'username', 'id', 'parent_id'));

            } catch (\Exception $e) {
                return $this->error('查询失败', ['errorMsg' => $e->getMessage()]);
            }
            $data = compact("total", 'list', 'statistics');
            return $this->success('successful', $data);
        }
        return view();
    }

    /**
     * 编辑管理组
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            //如果没有填写用户名，用户名默认是bw + 手机号
            if (isset($param['mobile']) && $param['mobile']) {
                if (!isset($param['username']) || !$param['username']) {
                    $param['username'] = 'bw' . $param['mobile'];
                }
            }
            $result = MemberModel::updateAdmin($param, true);
            if ($result) {
                return $this->success('操作成功');
            } else {
                return $this->error(MemberModel::getError());
            }
        }
        $id = $this->request->get('id');
        $field = $this->request->get('field');
        $data = AuthGroupAccess::getMemberFind($id);
        $list = MemberModel::select()->toArray();
        return view('form', ['data' => $data, 'list' => $list, "is_{$field}" => true]);

    }


    /**
     * 租戶詳情
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function detail()
    {
        $id = $this->request->get('id');
        $field = $this->request->get('field');
        $data = AuthGroupAccess::getMemberFind($id);
        $list = MemberModel::select()->toArray();
        $data['wallet'] = Wallet::where('member_id', $id)->find();
        $data['create_time_data'] = $data['create_time'] ? date('Y-m-d H:i:s', $data['create_time']) : 0;
        $data['login_time_data'] = $data['login_time'] ? date('Y-m-d H:i:s', $data['login_time']) : 0;

        if ($this->request->isAjax()) {
            return $this->success('success', ['data' => $data, 'list' => $list]);
        } else {
            return view('detail', ['data' => $data, 'list' => $list]);
        }
    }


    /**
     * 添加管理组
     * @return \think\Response
     */
    public function add(Request $request)
    {

        $member_id = 0;
        if ($this->request->isPost()) {
            $param = $this->request->param();
            //如果没有填写用户名，用户名默认是bw + 手机号
            if (isset($param['mobile']) && $param['mobile']) {
                if (!isset($param['username']) || !$param['username']) {
                    $param['username'] = 'bw' . $param['mobile'];
                }
            }
            if (!$param['safe_password']) $param['safe_password'] = '123456';
            if (!$param['password']) $param['password'] = 'a12345678';
            $result = MemberModel::createAdmin($param, $member_id, true, true, true);
            if ($result) {
                return $this->success('操作成功');
            } else {
                return $this->error(MemberModel::getError());
            }
        }
        return view('add', ['is_add' => true]);
    }

    /**
     * 更改开启状态
     * @return \think\Response
     */
    public function setStatus()
    {
        if (request()->isAjax()) {
            $id = input('id/d');
            $data = MemberModel::find($id);
            if ($data['status'] === 0) {
                $data['status'] = 1;
            } elseif ($data['status'] === 1) {
                $data['status'] = 0;
            };
            $data->save();
            return $this->success('success');

        }
    }

    /**
     * 发送站内信
     */
    public function sendMessage()
    {
        if (request()->isPost()) {
            $member_ids = request()->post('member_ids/d', 0);
            $msg = request()->post('msg/s', '');
            if (!$member_ids || !$msg) return $this->error('参数有误');
            try {
                Message::send(1, $this->uid, $member_ids, $msg);
                return $this->success('发送成功');
            } catch (Exception $e) {
                return $this->error($e->getMessage());
            }
        }
    }
}
